#!/usr/bin/env python
"""

    parse_slr_results.py
        parses the "outfile" from Tim Massingham's slr programme
    
"""
from __future__ import with_statement # needed for 2.5 ? Python < 2.6


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   options        


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

from optparse import OptionParser
import sys, os
import os.path
import StringIO

# add self to search path for testing
if __name__ == '__main__':
    exe_path = os.path.split(os.path.abspath(sys.argv[0]))[0]
    sys.path.append(os.path.abspath(os.path.join(exe_path,"..", "python_modules")))
    myname = os.path.split(sys.argv[0])[1]
    myname = os.path.splitext(myname)[0];
else:
    myname = __name__

from general_util import die_error
from custom_log import custom_log



parser = OptionParser(version="%prog 1.0")
parser.add_option("-v", "--verbose", dest = "verbose",
                  action="store_true", default=False,
                  help="Do not echo to shell but only print to log.")
parser.add_option("-L", "--log_file", dest="log_file",
                  metavar="FILE", 
                  type="string",
                  help="name and path of log file")
parser.add_option("-d", "--data_file", dest="data_file",
                  metavar="FILE", 
                  type="string",
                  help="name and path of data file")
parser.add_option("--log_parameters", dest="log_parameters",
                    action="store_true", default=False,
                    help="Print program parameters to log.")

parameters = [  
                "log_file",
                ]

mandatory_parameters = []

# parameters default to none
for parameter in parameters:
    parser.set_defaults(**{parameter: None}) 



if __name__ == '__main__':
    parser.set_defaults(log_file       = os.path.join(exe_path, "parse_slr_results.log"))

    # get help string
    f =StringIO.StringIO()
    parser.print_help(f)
    helpstr = f.getvalue()
    (options, remaining_args) = parser.parse_args()
    
    # mandatory options
    for parameter in mandatory_parameters:
        if options.__dict__[parameter] == None:
            die_error("Please specify a file in --%s.\n\n" % parameter + helpstr)



def save_option_parameters (logger):
    """
    Make a record of the program parameters so we can rerun things if necessary
    """
    programme_option_parameters = [myname + ".py"]
    
    
    store_false_options = set(i.dest for i in parser.option_list if i.action == "store_false")
    store_true_options  = set(i.dest for i in parser.option_list if i.action == "store_true")
    
    
    for option, value in options.__dict__.iteritems():
        if option in store_true_options:
            if value:
                programme_option_parameters.append("--" + option)
        elif option in store_false_options:
            if not value:
                programme_option_parameters.append("--" + option)
        else:
            if isinstance(value,str):
                programme_option_parameters.append("--" + option + " '" + str(value) + "'")

    programme_option_parameters = " ".join(programme_option_parameters)
    logger.info_unwrapped_to_log (programme_option_parameters + "\n")



#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   imports        


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

import StringIO
import re
import operator

import general_util
from general_util import die_error
from collections import defaultdict

#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Functions        


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888


    
    
#_________________________________________________________________________________________

#   collect_slr_results  

#_________________________________________________________________________________________
import re
spaces = re.compile(" +")

class SlrParsingError(Exception):
    def __init__(self, file_name, line_num, line, message):
        self.file_name = file_name
        self.line_num  = line_num
        self.line      = line
        self.message   = message
    def __str__(self):
        return "File [%s] #%d : %s\n[%s]" % (   self.file_name, self.line_num, 
                                                self.message, self.line)



#_________________________________________________________________________________________

#   parse_slr_positive_sites_file  

#_________________________________________________________________________________________
positive_site_category = ["90%", "99%", "90% corrected", "99% corrected"]
def parse_slr_positive_sites_file (file_name):
    """
        returns which positive sites at
    """

    slr_file = open(file_name)
    #
    #  get first line
    header_line = slr_file.readline()
    header_line = header_line.rstrip()
        
    
    if header_line[0] != '#':
        raise SlrParsingError(file_name, 1, header_line, 
                                "Header line does not start with '#'")
    fields = dict((v, i) for i, v in enumerate(header_line[1:].split()))
    if not 'Result' in fields:
        raise SlrParsingError(file_name, 1, header_line, 
                                "'Result' field not found.")
    if not 'Site' in fields:
        raise SlrParsingError(file_name, 1, header_line, 
                                "'Site' field not found.")
    result_colnum = fields['Result']
    sites_colnum  = fields['Site']
    
    positives_re = re.compile("(\++)")
    positive_sites = dict()
    for line in slr_file:
        data = line.rstrip().split()
        if len(data) <= result_colnum:
            continue
        
        match = positives_re.search(data[result_colnum])
        if match:
            position = int(data[sites_colnum]) - 1
            positive_sites[position] = len(match.group(1)) - 1
    return positive_sites

            
#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Main logic


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888




if __name__ == '__main__':
    from custom_log import custom_log
    logger = custom_log(myname, options.log_file)


    if options.log_parameters:
        save_option_parameters (logger)

    for file_name in sys.argv[1:]:
        positive_sites = parse_slr_positive_sites_file (file_name)
        print "%s:" % file_name
        for position, positive in sorted(positive_sites.iteritems()):
            print "\t%3d: %s" % (position + 1, positive_site_category[positive])

